package com.rjwh.dingdong.client.activity.more;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aishua.lib.utils.AsAppUtils;
import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.image.ImageListBrowseActivity;
import com.rjwh.dingdong.client.adapter.RelationShipGridAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.RelationItemData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.MoreBabyInfoPresenter;
import com.rjwh.dingdong.client.mvp.view.MoreBabyInfoView;
import com.rjwh.dingdong.client.util.BitmapFileUtil;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.Photo;
import com.rjwh.dingdong.client.util.ToastUtil;
import com.rjwh.dingdong.client.view.PhotoDialog;
import com.rjwh.dingdong.client.widget.RoundImageView;
import com.rjwh.dingdong.client.zxing.encoding.EncodingUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * @author Kay
 * @ClassName MoreBabyInfoActivity
 * @Description
 * @date 2016-7-13
 * @history 2016-7-13 author: description:
 */
public class MoreBabyInfoActivity extends BaseActivity implements MoreBabyInfoView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.baby_info_head_img)
    RoundImageView babyInfoHeadImg;
    @BindView(R.id.baby_info_nick_name_tv)
    TextView babyInfoNickNameTv;
    @BindView(R.id.baby_info_birth_tv)
    TextView babyInfoBirthTv;
    @BindView(R.id.baby_info_sex_tv)
    TextView babyInfoSexTv;
    @BindView(R.id.baby_info_relationship_tv)
    TextView babyInfoRelationshipTv;
    @BindView(R.id.baby_info_id_tv)
    TextView babyInfoIdTv;

    private static final int PICTAKEPHOTO = 1;
    private static final int PICINTUKU = 2;
    private static final int PHOTO_CUT = 3;

    private String cutImgPath;
    private List<RelationItemData> list;
    private int adapterPosition = -1;
    private SimpleDateFormat sdf;
    private Calendar calendar;
    private String initDateTime;
    private String dateTime;
    private String relationName;
    private String type;
    private String sextype;
    private String nameInput;
    private String relationType;
    private String relationInput;

    private MoreBabyInfoPresenter presenter;
    private PhotoDialog photoDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.more_baby_info_layout);
        ButterKnife.bind(this);
        initData();
        initRelationshipData();
        initView();
        presenter = new MoreBabyInfoPresenter(this, this);
    }

    private void initData() {
        sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        calendar = Calendar.getInstance();
    }

    private void initView() {
        initToolbarHelper();
        Glide.with(this).load(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYAVATAR)).dontAnimate().placeholder(R.drawable.icon_defult_avatar).error(R.drawable.icon_defult_avatar).into(babyInfoHeadImg);
        if (MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYNAME) != null) {
            babyInfoNickNameTv.setText(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYNAME));
        }
        babyInfoBirthTv.setText(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYBIRTHDAY));
        if (MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYSEX) != null && MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYSEX).equals("1")) {
            babyInfoSexTv.setText("男");
        } else {
            babyInfoSexTv.setText("女");
        }
        babyInfoRelationshipTv.setText(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USERCHENGWEI));
        babyInfoIdTv.setText(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYID));
        photoDialog = new PhotoDialog(this);
        photoDialog.setBackLsn(new PhotoDialog.onBackLsn() {
            @Override
            public void onClick(int type) {
                if (type == 0) {
                    Photo.systemPhotoAlbum(MoreBabyInfoActivity.this, PICINTUKU);
                } else {
                    RxPermissions.getInstance(getBaseContext())
                            .request(Manifest.permission.CAMERA)
                            .subscribe(new Action1<Boolean>() {
                                @Override
                                public void call(Boolean aBoolean) {
                                    LogUtil.d("获取到了运行权限:" + aBoolean);
                                    if (aBoolean) {
                                        cutImgPath = FileUtils.getTempImageStorageDirectory() + System
                                                .currentTimeMillis();
                                        Photo.startComer(MoreBabyInfoActivity.this, PICTAKEPHOTO,
                                                Uri.fromFile(new File(cutImgPath)));
                                    }
                                }
                            }, new Action1<Throwable>() {
                                @Override
                                public void call(Throwable throwable) {
                                    LogUtil.d("获取权限失败", throwable.getMessage());
                                }
                            });
                }
            }
        });
    }

    private void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        getSupportActionBar().setTitle(getResources().getString(R.string.more_baby_info));
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @OnClick({R.id.baby_info_head_img, R.id.baby_info_head_img_root_rl, R.id.baby_info_nick_name_root, R.id.baby_info_birth_root, R.id.baby_info_sex_root, R.id.baby_info_id_qr_code_root, R.id.baby_info_relationship_root})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baby_info_head_img_root_rl:
                photoDialog.show();
                break;
            case R.id.baby_info_nick_name_root:
                showNicknameDailog();
                break;
            case R.id.baby_info_birth_root:
                showBirthDailog();
                break;
            case R.id.baby_info_sex_root:
                showSetSexDailog();
                break;
            case R.id.baby_info_id_qr_code_root:
                showQrCodeDailog();
                break;
            case R.id.baby_info_relationship_root:
                showRelationShip();
                break;
            case R.id.baby_info_head_img:
                showAvatar();
                break;
        }
    }

    /**
     * 显示头像大图
     */
    private void showAvatar() {
        ArrayList<String> listImage = new ArrayList<>();
        String avatar = MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_BABYAVATAR);
        String bigAvatar = avatar.replace("/bp/", "/mp/");
        listImage.add(bigAvatar);
        Intent intentBrowse = new Intent(this, ImageListBrowseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("list", listImage);
        bundle.putBoolean("isAvatar", true);
        intentBrowse.putExtras(bundle);
        intentBrowse.putExtra("position", 0);
        startActivity(intentBrowse);
    }

    /**
     * 设置生日
     */
    private void showBirthDailog() {
        final AlertDialog dateDialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom)).create();
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout layout = (LinearLayout) inflater.inflate(
                R.layout.dialog_data_picker, null);
        dateDialog.setView(layout);
        dateDialog.show();
        Window window = dateDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setContentView(R.layout.dialog_data_picker);
        window.setGravity(Gravity.CENTER);
        DatePicker datePicker = (DatePicker) window.findViewById(R.id.dialog_datepicker);
        initDataPicker(datePicker, babyInfoBirthTv.getText().toString().trim());
        TextView cancelBtn = (TextView) window
                .findViewById(R.id.dialog_datepicker_cancel_btn);
        TextView conformBtn = (TextView) window
                .findViewById(R.id.dialog_datepicker_conform_btn);
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dateDialog.dismiss();
            }
        });
        conformBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dateDialog.dismiss();
                if (!AsStrUtils.isEmpty(dateTime)) {
                    showLoadDialog();
                    type = "3";
                    presenter.saveBabyData(dateTime, "3");
                } else {
                    babyInfoBirthTv.setText(initDateTime);
                }
            }
        });


    }

    private void initDataPicker(final DatePicker datePicker, String s) {
        if (!AsStrUtils.isEmpty(s)) {
            try {
                Date date = sdf.parse(s);
                String year = String.format("%tY", date);
                String month = String.format("%tm", date);
                String day = String.format(Locale.CHINA, "%td", date);
                datePicker.init(Integer.parseInt(year),
                        Integer.parseInt(month) - 1, Integer.parseInt(day),
                        new DatePicker.OnDateChangedListener() {
                            @Override
                            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                // 获得日历实例
                                calendar.set(datePicker.getYear(), datePicker.getMonth(),
                                        datePicker.getDayOfMonth());
                                dateTime = sdf.format(calendar.getTime());
                            }
                        });
                calendar.set(datePicker.getYear(), datePicker.getMonth(),
                        datePicker.getDayOfMonth());
                initDateTime = sdf.format(calendar.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            datePicker.init(calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
                        @Override
                        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            // 获得日历实例
                            calendar.set(datePicker.getYear(), datePicker.getMonth(),
                                    datePicker.getDayOfMonth());
                            dateTime = sdf.format(calendar.getTime());
                        }
                    });
            initDateTime = sdf.format(calendar.getTime());

        }
    }

    /**
     * 设置关系
     */
    private void showRelationShip() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        alertDialog.setView(inflater.inflate(R.layout.dialog_baby_info_relationship, null));
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_baby_info_relationship);
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        GridView relationship_gv = (GridView) window.findViewById(R.id.dialog_baby_info_relationship_gv);
        Button relationship_conform_btn = (Button) window.findViewById(R.id.dialog_baby_info_relationship_conform_btn);
        Button relationship_other_btn = (Button) window.findViewById(R.id.dialog_baby_info_relationship_other_btn);
        String chengwei = babyInfoRelationshipTv.getText().toString();
        relationName = chengwei;
        RelationShipGridAdapter relationShipGridAdapter = new RelationShipGridAdapter(this, chengwei);
        relationship_gv.setAdapter(relationShipGridAdapter);
        relationShipGridAdapter.appendToList(list);
        relationship_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RelationShipGridAdapter adapter = (RelationShipGridAdapter) parent.getAdapter();
                if (adapterPosition != position) {
                    adapterPosition = position;
                }
                adapter.setSelected(adapterPosition);
                RelationItemData item = (RelationItemData) adapter.getItem(position);
                relationName = item.getName();
                adapter.notifyDataSetChanged();

            }

        });

        relationship_conform_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                showLoadDialog();
                type = "4";
                relationType = "1";
                presenter.saveBabyData(relationName, "4");
            }
        });
        relationship_other_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                showOtherRelationshipDailog();
            }
        });
    }

    private void showOtherRelationshipDailog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        alertDialog.setView(inflater.inflate(R.layout.dialog_person_data_nick_name, null));
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_person_data_nick_name);
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        final EditText nick_name_et = (EditText) window.findViewById(R.id.dialog_person_data_nick_name_et);
        nick_name_et.setHint("输入和孩子的关系");
        ImageView nick_name_img = (ImageView) window.findViewById(R.id.dialog_person_data_nick_name_img);
        Button nick_name_conform_btn = (Button) window.findViewById(R.id.dialog_person_data_nick_name_conform_btn);
        Button nick_name_cancel_btn = (Button) window.findViewById(R.id.dialog_person_data_nick_name_cancel_btn);
        nick_name_img.setImageResource(R.drawable.icon_baby_info_relation_big);
        nick_name_conform_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                relationInput = nick_name_et.getText().toString();
                // 调用修改昵称接口
                if (!AsStrUtils.isEmpty(relationInput)) {
                    alertDialog.dismiss();
                    showLoadDialog();
                    type = "4";
                    relationType = "2";
                    presenter.saveBabyData(relationInput, "4");
                } else {
                    ToastUtil.showToast(MoreBabyInfoActivity.this, "你还没有输入内容");
                }

            }
        });
        nick_name_cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

    }

    private void initRelationshipData() {
        list = new ArrayList<>();
        RelationItemData relationItemDataBaba = new RelationItemData();
        relationItemDataBaba.setName("爸爸");
        relationItemDataBaba.setPicNomal(R.drawable.icon_relationship_baba_normal);
        relationItemDataBaba.setPicChecked(R.drawable.icon_relationship_baba_checked);
        RelationItemData relationItemDataMama = new RelationItemData();
        relationItemDataMama.setName("妈妈");
        relationItemDataMama.setPicNomal(R.drawable.icon_relationship_mama_normal);
        relationItemDataMama.setPicChecked(R.drawable.icon_relationship_mama_checked);
        RelationItemData relationItemDataYeye = new RelationItemData();
        relationItemDataYeye.setName("爷爷");
        relationItemDataYeye.setPicNomal(R.drawable.icon_relationship_yeye_normal);
        relationItemDataYeye.setPicChecked(R.drawable.icon_relationship_yeye_checked);
        RelationItemData relationItemDataNainai = new RelationItemData();
        relationItemDataNainai.setName("奶奶");
        relationItemDataNainai.setPicNomal(R.drawable.icon_relationship_nainai_normal);
        relationItemDataNainai.setPicChecked(R.drawable.icon_relationship_nainai_checked);
        RelationItemData relationItemDataWaigong = new RelationItemData();
        relationItemDataWaigong.setName("外公");
        relationItemDataWaigong.setPicNomal(R.drawable.icon_relationship_waigong_normal);
        relationItemDataWaigong.setPicChecked(R.drawable.icon_relationship_waigong_checked);
        RelationItemData relationItemDataWaipo = new RelationItemData();
        relationItemDataWaipo.setName("外婆");
        relationItemDataWaipo.setPicNomal(R.drawable.icon_relationship_waipo_normal);
        relationItemDataWaipo.setPicChecked(R.drawable.icon_relationship_waipo_checked);
        list.add(relationItemDataBaba);
        list.add(relationItemDataMama);
        list.add(relationItemDataYeye);
        list.add(relationItemDataNainai);
        list.add(relationItemDataWaigong);
        list.add(relationItemDataWaipo);
    }

    /**
     * 二维码
     */
    private void showQrCodeDailog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_baby_info_qrcode);
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        ImageView qrCodeImg = (ImageView) window.findViewById(R.id.dialog_baby_info_qrcode_img);
        //根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（350*350)
        String contentString = "tiandilixin://action?type=qrcode&babyid=" + MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYID);
        Bitmap qrCodeBitmap = EncodingUtils.createQRCode(contentString, 350, 350, null);
        qrCodeImg.setImageBitmap(qrCodeBitmap);
    }

    /**
     * 设置性别
     */
    private void showSetSexDailog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_baby_info_sex);
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        final TextView male_btn = (TextView) window.findViewById(R.id.dialog_baby_sex_male_tv);
        final TextView female_btn = (TextView) window.findViewById(R.id.dialog_baby_sex_female_tv);
        String sexText = babyInfoSexTv.getText().toString();
        if (!AsStrUtils.isEmpty(sexText)) {
            if (sexText.equals("男")) {
                male_btn.setTextColor(getResources().getColor(R.color.blue_button_nor));
            } else if (sexText.equals("女")) {
                female_btn.setTextColor(getResources().getColor(R.color.blue_button_nor));
            }
        }
        male_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                showLoadDialog();
                type = "2";
                sextype = "1";
                presenter.saveBabyData("1", "2");
            }
        });
        female_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                showLoadDialog();
                type = "2";
                sextype = "0";
                presenter.saveBabyData("0", "2");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICTAKEPHOTO:
                if (resultCode == RESULT_OK) {
                    if (AsAppUtils.hasSdcard()
                            && !AsStrUtils.isEmpty(cutImgPath)) {
                        File tempFile = new File(cutImgPath);
                        if (!tempFile.exists()) {
                            showToast("图片不存在！");
                            return;
                        }
                        LogUtil.d("cutImgPath:" + cutImgPath);
//                        uploadUserImage(cutImgPath);
                        startPhotoZoom(Uri.fromFile(tempFile));
                    } else {
                        showToast("未找到存储卡，无法存储照片！");
                    }
                }
                break;

            case PICINTUKU:
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    if (uri != null) {
                        cutImgPath = Photo.getPhotoPic(this, uri);
//                        uploadUserImage(cutImgPath);
                        startPhotoZoom(uri);
                    }
                }
                break;
            case PHOTO_CUT:
                if (data != null) {
                    // 获取裁剪后的图片路径
                    getImageToView(data);
                }
                break;
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 340);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CUT);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param data
     */
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            String urlpath = BitmapFileUtil.saveBitmap(photo);
            uploadUserImage(urlpath);
        }
    }

    /**
     * 上传头像
     */
    public void uploadUserImage(String cutImgPath) {
        showLoadDialog();
        final AjaxParams ps = new AjaxParams();
        ps.put("avatartype", "2");
        String outFile = FileUtils.getTempImageStorageDirectory() + System.currentTimeMillis() + ".png";
        try {
            ps.put("img",
                    BitmapFileUtil.compressBmpToFile(90, cutImgPath, outFile));
            LogUtil.e("MorePersonDataActivity", "img: " + BitmapFileUtil.compressBmpToFile(90, cutImgPath, outFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        MyApplication.http.post(LocalConstant.SEND_UPLOAD_USERIMAGE, ps,
                new AjaxCallBack<String>() {
                    @Override
                    public void onSuccess(String t) {
                        LogUtil.d("MoreBabyInfoActivity", "ps:" + ps);
                        LogUtil.d("MoreBabyInfoActivity", "上传宝宝头像:" + t);
                        super.onSuccess(t);
                        try {
                            JSONObject jb = new JSONObject(t);
                            JSONObject exeustate = jb
                                    .getJSONObject("exeustate");
                            String state = exeustate.getString("state");
                            String msg = exeustate.getString("msg");
                            if (!AsStrUtils.isEmpty(state) && state.equals("1") && !AsStrUtils.isEmpty(msg)) {
                                MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYAVATAR, msg);
                                Glide.with(MoreBabyInfoActivity.this).load(msg).dontAnimate().placeholder(R.drawable.icon_defult_avatar).error(R.drawable.icon_defult_avatar).into(babyInfoHeadImg);
                                ToastUtil.showToast(MoreBabyInfoActivity.this, "修改成功");
                            } else {
                                ToastUtil.showToast(MoreBabyInfoActivity.this, "上传失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.showToast(MoreBabyInfoActivity.this, "上传失败");
                        }
                        dismissLoadDialog();
                    }

                    @Override
                    public void onFailure(Throwable t, String strMsg) {
                        LogUtil.e("MoreBabyInfoActivity", "onFailure strMsg: " + strMsg);
                        super.onFailure(t, strMsg);
                        dismissLoadDialog();
                        ToastUtil.showToast(MoreBabyInfoActivity.this, "网络异常");
                    }
                });
    }

    /**
     * 设置昵称
     */
    private void showNicknameDailog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        alertDialog.setView(inflater.inflate(R.layout.dialog_person_data_nick_name, null));
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_person_data_nick_name);
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        final EditText nick_name_et = (EditText) window.findViewById(R.id.dialog_person_data_nick_name_et);
        ImageView nick_name_img = (ImageView) window.findViewById(R.id.dialog_person_data_nick_name_img);
        Button nick_name_conform_btn = (Button) window.findViewById(R.id.dialog_person_data_nick_name_conform_btn);
        Button nick_name_cancel_btn = (Button) window.findViewById(R.id.dialog_person_data_nick_name_cancel_btn);
        nick_name_img.setImageResource(R.drawable.icon_baby_info_nick_name_big);
        nick_name_et.setText(babyInfoNickNameTv.getText().toString());
        nick_name_conform_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                nameInput = nick_name_et.getText().toString();
                if (!AsStrUtils.isEmpty(nameInput)) {
                    showLoadDialog();
                    type = "1";
                    presenter.saveBabyData(nameInput, "1");
                } else {
                    ToastUtil.showToast(MoreBabyInfoActivity.this, "你还没有输入内容");
                }
            }
        });
        nick_name_cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

    }

    @Override
    public void showLoading() {
        showLoadDialog();
    }

    @Override
    public void dismissLoading() {
        dismissLoadDialog();
    }

    @Override
    public void loadData() {
        switch (type) {
            case "1":
                babyInfoNickNameTv.setText(nameInput);
                MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYNAME, nameInput);
                break;
            case "2":
                if (sextype.equals("1")) {
                    babyInfoSexTv.setText("男");
                    MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYSEX, "1");
                } else {
                    babyInfoSexTv.setText("女");
                    MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYSEX, "2");
                }
                break;
            case "3":
                babyInfoBirthTv.setText(dateTime);
                MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYBIRTHDAY, dateTime);
                break;
            case "4":
                if (relationType.equals("1")) {
                    babyInfoRelationshipTv.setText(relationName);
                    MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_USERCHENGWEI, relationName);
                } else {
                    babyInfoRelationshipTv.setText(relationInput);
                    MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_USERCHENGWEI, relationInput);
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
    }
}
